package com.example.finaltool.aop;

import com.example.finaltool.annotations.Timer;
import com.example.finaltool.utils.PrintUtils;
import com.example.finaltool.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dengbw
 * @date 2021/10/13 11:12 上午
 */
@Slf4j
@Aspect
@Component
public class TimerAspect {
    private Map<String, LocalDateTime> starts;

    @Pointcut("@annotation(timer)")
    private void pointCut(Timer timer) {
    }

    @Before(value = "pointCut(timer)", argNames = "timer")
    public void before(Timer timer) {
        String name = timer.value();
        if (starts == null) {
            starts = new HashMap<>();
        }
        starts.put(name, LocalDateTime.now());
        PrintUtils.stepStart(name);
    }
    @AfterReturning(value = "pointCut(timer)", argNames = "timer")
    public void after(Timer timer) {
        if (!starts.containsKey(timer.value())) {
            PrintUtils.stepFinish(timer.value());
            return;
        }
        PrintUtils.stepFinish(timer.value(), TimeUtils.duration(starts.get(timer.value())));
    }
}
